/**
 * 微表情识别系统 - 前端JavaScript
 */

document.addEventListener('DOMContentLoaded', function() {
    // 获取DOM元素
    const uploadArea = document.getElementById('upload-area');
    const fileInput = document.getElementById('file-input');
    const uploadText = document.querySelector('.upload-text');
    const processingStatus = document.querySelector('.processing-status');
    const resultsArea = document.querySelector('.results-area');
    const loadingSpinner = document.querySelector('.loading-spinner');
    const errorMessage = document.getElementById('error-message');
    
    // 初始化
    hideElement(processingStatus);
    hideElement(resultsArea);
    
    // 拖放功能
    ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
        uploadArea.addEventListener(eventName, preventDefaults, false);
    });
    
    function preventDefaults(e) {
        e.preventDefault();
        e.stopPropagation();
    }
    
    ['dragenter', 'dragover'].forEach(eventName => {
        uploadArea.addEventListener(eventName, highlight, false);
    });
    
    ['dragleave', 'drop'].forEach(eventName => {
        uploadArea.addEventListener(eventName, unhighlight, false);
    });
    
    function highlight() {
        uploadArea.classList.add('highlight');
    }
    
    function unhighlight() {
        uploadArea.classList.remove('highlight');
    }
    
    // 处理拖放上传
    uploadArea.addEventListener('drop', handleDrop, false);
    
    function handleDrop(e) {
        const dt = e.dataTransfer;
        const files = dt.files;
        if (files.length) {
            fileInput.files = files;
            handleFiles(files);
        }
    }
    
    // 处理文件选择
    fileInput.addEventListener('change', function() {
        if (fileInput.files.length) {
            handleFiles(fileInput.files);
        }
    });
    
    // 处理文件上传和处理
    function handleFiles(files) {
        const file = files[0]; // 目前只处理一个文件
        
        // 验证文件类型 (视频或图像)
        if (!file.type.match('video.*') && !file.type.match('image.*')) {
            showError('请上传视频或图像文件');
            return;
        }
        
        // 显示处理中状态
        uploadText.textContent = `正在处理: ${file.name}`;
        showElement(processingStatus);
        hideElement(resultsArea);
        
        // 创建FormData对象
        const formData = new FormData();
        formData.append('file', file);
        
        // 发送到服务器
        fetch('/api/detect', {
            method: 'POST',
            body: formData
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('上传和处理过程中出错');
            }
            return response.json();
        })
        .then(data => {
            // 处理完成，展示结果
            hideElement(processingStatus);
            console.log('API响应数据:', data); // 添加日志以便调试
            displayResults(data);
            showElement(resultsArea); // 确保显示结果区域
        })
        .catch(error => {
            hideElement(processingStatus);
            showError(error.message);
        });
    }
    
    // 显示结果
    function displayResults(data) {
        // 清除旧结果
        const resultsContainer = document.getElementById('results-container');
        resultsContainer.innerHTML = '';
        
        if (data.error) {
            showError(data.error);
            return;
        }
        
        // 如果有缩略图，显示
        if (data.thumbnail_url) {
            console.log('缩略图URL:', data.thumbnail_url); // 添加日志以便调试
            
            const thumbnailContainer = document.createElement('div');
            thumbnailContainer.className = 'result-card mb-4';
            
            // 检查URL是否以/开头
            const thumbnailUrl = data.thumbnail_url.startsWith('/') 
                ? data.thumbnail_url 
                : '/' + data.thumbnail_url;
                
            // 根据文件类型选择显示视频还是图像
            const isVideo = thumbnailUrl.match(/\.(mp4|webm|avi|mov)$/i);
            
            let mediaElement = '';
            if (isVideo) {
                mediaElement = `
                    <video id="emotion-video" controls class="img-fluid rounded">
                        <source src="${thumbnailUrl}" type="video/mp4">
                        您的浏览器不支持视频播放
                    </video>
                    <div id="timeline-emotions-container" class="mt-3">
                        <div class="timeline-emotions-header mb-2">
                            <h5 class="mb-0">当前微表情: <span id="current-emotion-label" class="badge bg-primary">分析中...</span></h5>
                        </div>
                        <div class="analysis-settings mt-3 mb-2">
                            <div class="row">
                                <div class="col-md-6">
                                    <label for="analysis-interval" class="form-label">分析间隔 (秒):</label>
                                    <input type="range" class="form-range" id="analysis-interval" min="0.5" max="3" step="0.5" value="1">
                                    <div class="text-center"><span id="interval-value">1</span>秒</div>
                                </div>
                                <div class="col-md-6">
                                    <label for="stability-threshold" class="form-label">稳定性阈值:</label>
                                    <input type="range" class="form-range" id="stability-threshold" min="1" max="5" step="1" value="2">
                                    <div class="text-center"><span id="threshold-value">2</span>次</div>
                                </div>
                            </div>
                        </div>
                        <div class="realtime-emotion-description mt-2">
                            <p class="text-muted small">视频播放时将实时分析当前帧的微表情</p>
                        </div>
                    </div>`;
            } else {
                mediaElement = `<img src="${thumbnailUrl}" alt="处理的媒体" class="img-fluid rounded">`;
            }
            
            thumbnailContainer.innerHTML = `
                <div class="result-card-header">处理的媒体</div>
                <div class="result-card-body text-center">
                    ${mediaElement}
                </div>
            `;
            resultsContainer.appendChild(thumbnailContainer);
            
            // 如果是视频，初始化实时微表情分析
            if (isVideo) {
                initializeEmotionTimeline(data.timeline_emotions, data.video_info);
                
                // 初始化分析设置滑块
                const intervalSlider = document.getElementById('analysis-interval');
                const intervalValue = document.getElementById('interval-value');
                const thresholdSlider = document.getElementById('stability-threshold');
                const thresholdValue = document.getElementById('threshold-value');
                
                // 分析间隔滑块事件
                if (intervalSlider && intervalValue) {
                    intervalSlider.addEventListener('input', function() {
                        intervalValue.textContent = this.value;
                        // 更新视频元素的分析间隔设置
                        const video = document.getElementById('emotion-video');
                        if (video) {
                            video._analysisInterval = parseFloat(this.value);
                        }
                    });
                }
                
                // 稳定性阈值滑块事件
                if (thresholdSlider && thresholdValue) {
                    thresholdSlider.addEventListener('input', function() {
                        thresholdValue.textContent = this.value;
                        // 更新视频元素的稳定性阈值设置
                        const video = document.getElementById('emotion-video');
                        if (video) {
                            video._stabilityThreshold = parseInt(this.value);
                        }
                    });
                }
            }
        } else {
            console.warn('API响应中没有缩略图URL'); // 添加警告日志
            
            // 即使没有缩略图也创建一个占位符容器
            const thumbnailContainer = document.createElement('div');
            thumbnailContainer.className = 'result-card mb-4';
            thumbnailContainer.innerHTML = `
                <div class="result-card-header">处理的媒体</div>
                <div class="result-card-body text-center">
                    <p>无法显示媒体文件预览</p>
                </div>
            `;
            resultsContainer.appendChild(thumbnailContainer);
        }
        
        // 显示情绪结果
        if (data.emotions && Array.isArray(data.emotions) && data.emotions.length > 0) {
            const emotionsCard = document.createElement('div');
            emotionsCard.className = 'result-card mb-4';
            
            let emotionsHtml = `
                <div class="result-card-header">检测到的微表情</div>
                <div class="result-card-body">
                    <div class="chart-container">
                        <canvas id="emotions-chart"></canvas>
                    </div>
                    <table class="results-table table mt-3">
                        <thead>
                            <tr>
                                <th>情绪</th>
                                <th>概率</th>
                            </tr>
                        </thead>
                        <tbody>
            `;
            
            // 准备图表数据
            const labels = [];
            const chartData = [];
            const backgroundColors = [];
            
            // 颜色映射
            const colorMap = {
                '生气': '#FF6384',
                '厌恶': '#7AC142',
                '恐惧': '#C9CBCF',
                '高兴': '#4BC0C0',
                '悲伤': '#9966FF',
                '惊讶': '#FFCD56',
                '中性': '#36A2EB',
                'angry': '#FF6384',
                'disgust': '#7AC142',
                'fear': '#C9CBCF',
                'happy': '#4BC0C0', 
                'sad': '#9966FF',
                'surprise': '#FFCD56',
                'neutral': '#36A2EB'
            };
            
            // 填充表格和图表数据
            data.emotions.forEach(emotion => {
                // 确保emotion对象有必要的属性
                if (emotion && emotion.label && typeof emotion.probability === 'number') {
                    const label = emotion.label;
                    const probability = emotion.probability;
                    const percentage = (probability * 100).toFixed(2);
                    const color = colorMap[label.toLowerCase()] || '#36A2EB';
                    
                    labels.push(label);
                    chartData.push(probability);
                    backgroundColors.push(color);
                    
                    emotionsHtml += `
                        <tr>
                            <td><span class="emotion-badge ${label.toLowerCase()}">${label}</span></td>
                            <td>${percentage}%</td>
                        </tr>
                    `;
                }
            });
            
            emotionsHtml += `
                        </tbody>
                    </table>
                </div>
            `;
            
            emotionsCard.innerHTML = emotionsHtml;
            resultsContainer.appendChild(emotionsCard);
            
            // 创建图表
            setTimeout(() => {
                const ctx = document.getElementById('emotions-chart').getContext('2d');
                new Chart(ctx, {
                    type: 'doughnut',
                    data: {
                        labels: labels,
                        datasets: [{
                            data: chartData,
                            backgroundColor: backgroundColors,
                            hoverOffset: 4
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                position: 'bottom'
                            }
                        }
                    }
                });
            }, 100);
        } else {
            // 如果没有情绪数据，显示消息
            const noDataCard = document.createElement('div');
            noDataCard.className = 'result-card mb-4';
            noDataCard.innerHTML = `
                <div class="result-card-header">检测结果</div>
                <div class="result-card-body text-center">
                    <p>未能检测到情绪数据。请尝试上传不同的媒体文件。</p>
                </div>
            `;
            resultsContainer.appendChild(noDataCard);
        }
        
        // 如果有时间线情绪数据，添加时间线图表
        if (data.timeline_emotions && Array.isArray(data.timeline_emotions) && data.timeline_emotions.length > 0) {
            const timelineCard = document.createElement('div');
            timelineCard.className = 'result-card mb-4';
            
            let timelineHtml = `
                <div class="result-card-header">视频微表情时间线</div>
                <div class="result-card-body">
                    <div class="chart-container">
                        <canvas id="timeline-chart"></canvas>
                    </div>
                    <div class="timeline-legend mt-3">
                        <p class="text-muted small">该图表显示了视频中不同时间点检测到的主要情绪。</p>
                    </div>
                </div>
            `;
            
            timelineCard.innerHTML = timelineHtml;
            resultsContainer.appendChild(timelineCard);
            
            // 创建时间线图表
            setTimeout(() => {
                createTimelineChart(data.timeline_emotions);
            }, 100);
        }
        
        // 显示结果区域
        showElement(document.querySelector('.results-area'));
    }
    
    function hideElement(element) {
        if (element) {
            element.style.display = 'none';
        }
    }
    
    function showElement(element) {
        if (element) {
            element.style.display = 'block';
        }
    }
    
    function showError(message) {
        errorMessage.textContent = message;
        showElement(errorMessage);
        
        // 5秒后隐藏错误信息
        setTimeout(() => {
            hideElement(errorMessage);
        }, 5000);
    }

    // 初始化情绪时间线显示
    function initializeEmotionTimeline(timelineData, videoInfo) {
        const video = document.getElementById('emotion-video');
        const timelineContainer = document.getElementById('timeline-emotions-container');
        const currentEmotionLabel = document.getElementById('current-emotion-label');
        
        if (!video || !timelineContainer || !currentEmotionLabel) return;
        
        // 初始化分析设置
        video._analysisInterval = 1.0; // 默认分析间隔为1秒
        video._stabilityThreshold = 2; // 默认稳定性阈值为2
        
        // 创建一个Canvas用于实时分析
        const videoCanvas = document.createElement('canvas');
        videoCanvas.style.display = 'none';
        document.body.appendChild(videoCanvas);
        const ctx = videoCanvas.getContext('2d');
        
        // 防抖动变量
        let lastEmotion = null;
        let emotionChangeCounter = 0;
        
        // 视频时间更新事件
        video.addEventListener('timeupdate', function() {
            // 实时分析当前帧
            if (video.paused || video.ended) return;
            
            const currentTime = video.currentTime;
            
            // 使用用户设置的分析间隔
            const analysisInterval = video._analysisInterval || 1.0;
            
            // 使用用户设置的稳定性阈值
            const stabilityThreshold = video._stabilityThreshold || 2;
            
            // 按照设置的间隔分析
            if (!video._lastAnalysisTime || (currentTime - video._lastAnalysisTime) >= analysisInterval) {
                video._lastAnalysisTime = currentTime;
                
                // 捕获当前帧
                captureVideoFrame(video, videoCanvas, ctx).then(imageData => {
                    if (!imageData) return;
                    
                    // 发送到服务器进行分析
                    analyzeVideoFrame(imageData, currentTime).then(result => {
                        if (result && result.top_emotion) {
                            // 防抖动处理
                            if (lastEmotion === result.top_emotion) {
                                emotionChangeCounter++;
                                // 当同一情绪连续出现多次后才更新显示
                                if (emotionChangeCounter >= stabilityThreshold) {
                                    updateEmotionLabel(currentEmotionLabel, result.top_emotion);
                                }
                            } else {
                                // 情绪变化，重置计数器
                                lastEmotion = result.top_emotion;
                                emotionChangeCounter = 1;
                            }
                        }
                    }).catch(error => {
                        console.error('分析视频帧时出错:', error);
                    });
                });
            }
        });
        
        // 视频播放状态改变
        video.addEventListener('play', function() {
            // 开始播放时重置分析时间和情绪状态
            video._lastAnalysisTime = null;
            lastEmotion = null;
            emotionChangeCounter = 0;
            updateEmotionLabel(currentEmotionLabel, "分析中...");
        });
        
        // 视频暂停或结束
        video.addEventListener('pause', function() {
            // 不需要继续分析
        });
        
        video.addEventListener('ended', function() {
            updateEmotionLabel(currentEmotionLabel, "分析完成");
        });
    }

    // 捕获视频当前帧
    function captureVideoFrame(video, canvas, ctx) {
        return new Promise((resolve, reject) => {
            try {
                if (video.paused || video.ended) {
                    resolve(null);
                    return;
                }
                
                // 调整canvas大小匹配视频
                canvas.width = video.videoWidth;
                canvas.height = video.videoHeight;
                
                // 绘制当前帧到canvas
                ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
                
                // 获取图像数据
                canvas.toBlob(blob => {
                    if (!blob) {
                        resolve(null);
                        return;
                    }
                    resolve(blob);
                }, 'image/jpeg', 0.8);
            } catch (error) {
                console.error('捕获视频帧时出错:', error);
                resolve(null);
            }
        });
    }

    // 发送帧到服务器进行分析
    function analyzeVideoFrame(imageData, timestamp) {
        return new Promise((resolve, reject) => {
            const formData = new FormData();
            formData.append('frame', imageData, 'frame.jpg');
            formData.append('timestamp', timestamp);
            
            fetch('/api/analyze_frame', {
                method: 'POST',
                body: formData
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('服务器响应错误');
                }
                return response.json();
            })
            .then(data => {
                resolve(data);
            })
            .catch(error => {
                console.error('发送帧分析请求时出错:', error);
                reject(error);
            });
        });
    }

    // 更新情绪标签，添加动画效果
    function updateEmotionLabel(label, emotion) {
        if (!label) return;
        
        // 移除旧的动画类
        label.classList.remove('fade-in-emotion');
        
        // 触发重绘
        void label.offsetWidth;
        
        // 更新文本
        label.textContent = emotion;
        
        // 添加动画类
        label.classList.add('fade-in-emotion');
        
        // 根据情绪类型更改标签颜色
        label.className = 'badge fade-in-emotion';
        if (emotion === '高兴') label.classList.add('bg-success');
        else if (emotion === '悲伤') label.classList.add('bg-primary');
        else if (emotion === '生气') label.classList.add('bg-danger');
        else if (emotion === '惊讶') label.classList.add('bg-warning');
        else if (emotion === '恐惧') label.classList.add('bg-info');
        else if (emotion === '厌恶') label.classList.add('bg-secondary');
        else if (emotion === '中性') label.classList.add('bg-light', 'text-dark');
        else label.classList.add('bg-primary');
    }

    // 格式化时间为 mm:ss 格式
    function formatTime(seconds) {
        seconds = Math.round(seconds);
        const mins = Math.floor(seconds / 60);
        const secs = seconds % 60;
        return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
    }

    // 创建时间线图表
    function createTimelineChart(timelineData) {
        // 准备图表数据
        const timestamps = [];
        const emotionDatasets = {};
        const colorMap = {
            '生气': '#FF6384',
            '厌恶': '#7AC142',
            '恐惧': '#C9CBCF',
            '高兴': '#4BC0C0',
            '悲伤': '#9966FF',
            '惊讶': '#FFCD56',
            '中性': '#36A2EB'
        };
        
        // 收集所有情绪标签
        const allEmotions = new Set();
        timelineData.forEach(point => {
            if (point.emotions && point.emotions.length > 0) {
                point.emotions.forEach(emotion => {
                    allEmotions.add(emotion.label);
                });
            }
        });
        
        // 为每种情绪创建空的数据集
        allEmotions.forEach(emotion => {
            emotionDatasets[emotion] = {
                label: emotion,
                data: Array(timelineData.length).fill(0),
                borderColor: colorMap[emotion] || '#36A2EB',
                backgroundColor: (colorMap[emotion] || '#36A2EB') + '40', // 添加透明度
                tension: 0.2
            };
        });
        
        // 填充数据集
        timelineData.forEach((point, index) => {
            // 添加时间戳
            timestamps.push(formatTime(point.timestamp));
            
            // 填充情绪概率
            if (point.emotions && point.emotions.length > 0) {
                point.emotions.forEach(emotion => {
                    if (emotionDatasets[emotion.label]) {
                        emotionDatasets[emotion.label].data[index] = emotion.probability;
                    }
                });
            }
        });
        
        // 创建图表
        const ctx = document.getElementById('timeline-chart').getContext('2d');
        new Chart(ctx, {
            type: 'line',
            data: {
                labels: timestamps,
                datasets: Object.values(emotionDatasets)
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                interaction: {
                    mode: 'index',
                    intersect: false
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        max: 1,
                        title: {
                            display: true,
                            text: '情绪概率'
                        }
                    },
                    x: {
                        title: {
                            display: true,
                            text: '时间 (秒)'
                        }
                    }
                }
            }
        });
    }
}); 